<template>
  <div class="article">
    <el-form ref="articleForm" :model="article" label-width="120px">
      <h2>文章采编</h2>
      <el-form-item label="标题">
        <el-input v-model="article.title"></el-input>
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="article.author"></el-input>
      </el-form-item>
      <el-form-item label="类别">
        <el-select v-model="article.categoryId" placeholder="请选择类别">
          <el-option
            v-for="category in categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 原文链接输入 -->
      <el-form-item label="原文链接">
        <el-input v-model="article.refUrl"></el-input>
      </el-form-item>
      <!-- 文章简介 -->
      <el-form-item label="文章简介">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入文章简介"
          v-model="article.summary"
        ></el-input>
        <!-- margin 设为0 -->
        <el-button type="text" style="float: right margin: 0px;" @click="autosummary">自动生成简介</el-button>
      </el-form-item>
      <el-form-item label="封面图片">
        <el-upload
          class="avatar-uploader"
          :action="'/api/file/upload'"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :before-upload="beforeUpload"
        >
          <img v-if="article.coverUrl" :src="article.coverUrl" class="avatar" style="height: 200px;" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <div class="editor"></div>
      <quill-editor
        v-model="article.content"
        ref="myQuillEditor"
        :options="editorOption"
        @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)"
        @change="onEditorChange($event)"
        @ready="onEditorReady($event)"
      >
      </quill-editor>
      
      <!-- 添加其他字段的表单项 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存草稿</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { quillEditor, Quill } from 'vue-quill-editor';
import { container, ImageExtend, QuillWatch } from 'quill-image-extend-module';

import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';

// import ImageResize from 'quill-image-resize-module'
import { ImageResize } from 'quill-image-resize-module';
Quill.register('modules/ImageExtend', ImageExtend);
Quill.register('modules/ImageResize', ImageResize);
import NProgress from 'nprogress';

import axios from 'axios';

export default {
  name: 'adminarticle',
  components: {
    quillEditor,
  },
  methods: {
    // 失去焦点事件
    onEditorBlur(quill) {
      // console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      // console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // toolbar标题
      const titleConfig = [
        { Choice: '.ql-insertMetric', title: '跳转配置' },
        { Choice: '.ql-bold', title: '加粗' },
        { Choice: '.ql-italic', title: '斜体' },
        { Choice: '.ql-underline', title: '下划线' },
        { Choice: '.ql-header', title: '段落格式' },
        { Choice: '.ql-strike', title: '删除线' },
        { Choice: '.ql-blockquote', title: '块引用' },
        { Choice: '.ql-code', title: '插入代码' },
        { Choice: '.ql-code-block', title: '插入代码段' },
        { Choice: '.ql-font', title: '字体' },
        { Choice: '.ql-size', title: '字体大小' },
        { Choice: '.ql-list[value="ordered"]', title: '编号列表' },
        { Choice: '.ql-list[value="bullet"]', title: '项目列表' },
        { Choice: '.ql-direction', title: '文本方向' },
        { Choice: '.ql-header[value="1"]', title: 'h1' },
        { Choice: '.ql-header[value="2"]', title: 'h2' },
        { Choice: '.ql-align', title: '对齐方式' },
        { Choice: '.ql-color', title: '字体颜色' },
        { Choice: '.ql-background', title: '背景颜色' },
        { Choice: '.ql-image', title: '图像' },
        { Choice: '.ql-video', title: '视频' },
        { Choice: '.ql-link', title: '添加链接' },
        { Choice: '.ql-formula', title: '插入公式' },
        { Choice: '.ql-clean', title: '清除字体格式' },
        { Choice: '.ql-script[value="sub"]', title: '下标' },
        { Choice: '.ql-script[value="super"]', title: '上标' },
        { Choice: '.ql-indent[value="-1"]', title: '向左缩进' },
        { Choice: '.ql-indent[value="+1"]', title: '向右缩进' },
        { Choice: '.ql-header .ql-picker-label', title: '标题大小' },
        {
          Choice: '.ql-header .ql-picker-item[data-value="1"]',
          title: '标题一',
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="2"]',
          title: '标题二',
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="3"]',
          title: '标题三',
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="4"]',
          title: '标题四',
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="5"]',
          title: '标题五',
        },
        {
          Choice: '.ql-header .ql-picker-item[data-value="6"]',
          title: '标题六',
        },
        { Choice: '.ql-header .ql-picker-item:last-child', title: '标准' },
        {
          Choice: '.ql-size .ql-picker-item[data-value="small"]',
          title: '小号',
        },
        {
          Choice: '.ql-size .ql-picker-item[data-value="large"]',
          title: '大号',
        },
        {
          Choice: '.ql-size .ql-picker-item[data-value="huge"]',
          title: '超大号',
        },
        { Choice: '.ql-size .ql-picker-item:nth-child(2)', title: '标准' },
        { Choice: '.ql-align .ql-picker-item:first-child', title: '居左对齐' },
        {
          Choice: '.ql-align .ql-picker-item[data-value="center"]',
          title: '居中对齐',
        },
        {
          Choice: '.ql-align .ql-picker-item[data-value="right"]',
          title: '居右对齐',
        },
        {
          Choice: '.ql-align .ql-picker-item[data-value="justify"]',
          title: '两端对齐',
        },
      ];
      for (let item of titleConfig) {
        let tip = document.querySelector('.quill-editor ' + item.Choice);
        if (!tip) continue;
        tip.setAttribute('title', item.title);
      }
      console.log('editor ready!', quill);
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      // console.log("editor change!", quill, html, text);
      // console.log(html);
      this.article.content = html;
      this.article.plainText = text;
    },
    beforeUpload(file) {},
    // 上传成功时触发
    uploadSuccess(res) {
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, 'image', res.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息，需引入Message
        this.$message.error('图片插入失败！');
      }
    },
    submitForm() {
      this.$refs.articleForm.validate((valid) => {
        if (valid) {
          axios
            .post('/api/article', this.article)
            .then((response) => {
              NProgress.done();
              // 提交成功的提示
              // alert('提交成功');
              this.$message({
                message: '提交成功',
                type: 'success',
              });              
              // 跳转到新的路由，例如一个提交成功的页面
              this.$router.push({ name: 'articles' });
            })
            .catch((error) => {
              // 提交失败的提示
              this.$message.error('提交失败');

              // 这里不需要做路由跳转，用户将留在当前页面
            });
        } else {
          // 表单验证失败的提示
          alert('表单验证失败');
          return false;
        }
      });
    },
    fetchCategories() {
      axios
        .get('/api/category/list') // 替换为你的后端API
        .then((response) => {
          this.categories = response.data.data; // 假设后端返回类别列表
          NProgress.done();
        })
        .catch((error) => {
          console.error('获取类别列表失败', error);
        });
    },
    async loadArticle(id) {
      try {
        const response = await axios.get(`/api/article/${id}`);
        NProgress.done();
        this.article = response.data.data; // 假设后端直接返回文章数据
      } catch (error) {
        console.error('获取文章详细信息失败', error);
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    uploadSuccess(res) {
      if (res) {
        this.article.coverUrl = res.url;
      } else {
        this.$message.error(res);
      }
    },
    fileUpload() {
      return "/api/file/upload";
    },
    autosummary() {
      axios.post("/api/llm/summary", encodeURI(this.article.plainText))
      .then((response) => {
        console.log(response.data);
        this.article.summary = response.data.data;
        NProgress.done();
      })
    },
  },
  data() {
    return {
      isEditMode: false, // 是否为编辑模式
      article: {
        id: null, // 如果是新建文章，id可能为空
        categoryId: null,
        userId: null,
        title: "",
        content: "",
        plainText: "",
        summary: "",
        refUrl: "",
        author: "",
        editorId: null,
        coverUrl: '',
        watch: null,
        createTime: null,
        updateTime: null,
        isDeleted: null,
        publishTime: null,
        status: null,
      },
      categories: [], // 类别列表初始化为空数组
      fileUpload: null,
      // 富文本编辑器配置
      editorOption: {
        modules: {
          ImageExtend: {
            loading: true,
            name: 'file',
            size: 8,
            action: '/api/file/upload',
            response: (res) => {
              console.log(res);
              return res.url;
            },
            // headers: (xhr,formData) => {
            //   //xhr.setRequestHeader(
            //   //  "X-Nideshop-Token",
            //   //  localStorage.getItem("token")
            //   //);
            // }, // 可选参数 设置请求头部
            sizeError: () => {
              return this.$message.error('粘贴图片大小不能超过8MB!');
            }, // 图片超过大小的回调
          },
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
              ['blockquote', 'code-block'], //引用，代码块
              [{ header: 1 }, { header: 2 }], // 几级标题
              [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
              [{ script: 'sub' }, { script: 'super' }], // 下角标，上角标
              [{ indent: '-1' }, { indent: '+1' }], // 缩进
              [{ direction: 'rtl' }], // 文字输入方向
              [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
              [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题
              [{ color: [] }, { background: [] }], // 颜色选择
              [{ font: [] }], // 字体
              [{ align: [] }], // 居中
              ['link', 'image'],
              ['clean'],
            ],
            handlers: {
              image: function () {
                QuillWatch.emit(this.quill.id);
              },
            },
          },
          // 如果使用图片可调整大小，加入如下配置
          ImageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white',
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar'],
          },
        },
      },
    };
  },
  created() {
    this.fetchCategories(); // 获取类别数据
  },
  mounted() {
    // 检查路由参数，确定模式
    if (this.$route.params.id) {
      this.isEditMode = true;
      this.loadArticle(this.$route.params.id);
    }
  },
};
</script>

<style scoped>
.el-form {
  padding: 50px;
  border: #ccc 5px solid;
  border-radius: 10px;
  background-color: white;
  width: 70%;
  margin: 50px auto;
}

.el-form-item {
  width: 600px;
}

.el-button {
  margin-top: 50px;
  margin-left: 440px;
}

h2 {
  margin: 0 auto;
  margin-top: 0;
  margin-bottom: 20px;
  text-align: center;
}

.el-button--text {
  margin: 0;
}
</style>
